//
//  LGFAudioPlayer.swift
//  Auscultation
//
//  Created by 来 on 2020/12/12.
//

import UIKit

protocol LGFAudioPlayerDelegate: class {
    func LGFAudioPlayerState(_ player: STKAudioPlayer)
    func LGFAudioPlayerRun(_ player: STKAudioPlayer)
    func LGFAudioPlayerStop(_ player: STKAudioPlayer)
}
class LGFAudioPlayer: NSObject {
    
    weak var delegate: LGFAudioPlayerDelegate?
    
    var play_timer: Timer?
    
    override init() {
        super.init()
        reset()
    }
    
    // 音频播放器
    var audioPlayer: STKAudioPlayer!
    
    //当前播放状态
    var state: STKAudioPlayerState = []
    
    // 播放
    func playFile(_ url: String) {
        audioPlayer.play(STKAudioPlayer.dataSource(from: URL.init(fileURLWithPath: url)))
        play_timer = Timer.lgf_RunTimer(self, S: 0.0001) { [weak self] (timer) in
            self?.delegate?.LGFAudioPlayerRun(self!.audioPlayer)
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "LGFAudioPlayerRun"), object: self!.audioPlayer)
        }
    }
    func playOnLine(_ url: String) {
        audioPlayer.play(url)
        play_timer = Timer.lgf_RunTimer(self, S: 0.0001) { [weak self] (timer) in
            self?.delegate?.LGFAudioPlayerRun(self!.audioPlayer)
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "LGFAudioPlayerRun"), object: self!.audioPlayer)
        }
    }
    
    // 指定位置播放
    func seek(_ value: Float) {
        audioPlayer.seek(toTime: Double(value))
    }
    
    // 停止
    func stop() {
        debugPrint("STKAudioPlayer 已经停止")
        audioPlayer?.stop()
        play_timer?.lgf_StopTimer()
        play_timer = nil
    }
    
    // 释放
    func dispose() {
        if audioPlayer != nil {
            audioPlayer.clearQueue()
            audioPlayer.dispose()
        }
    }
    
    // 恢复
    func resume() {
        if self.state == .paused {
            audioPlayer.resume()
            play_timer?.lgf_Resume()
        }
    }
    
    // 暂停
    func paused() {
        if self.state == .playing {
            audioPlayer.pause()
            play_timer?.lgf_Paused()
        }
    }
    
    // 重置
    func reset() {
        var options = STKAudioPlayerOptions()
        options.flushQueueOnSeek = true
        options.enableVolumeMixer = true
        audioPlayer = STKAudioPlayer(options: options)
        audioPlayer.meteringEnabled = true
        audioPlayer.volume = 1
        audioPlayer.delegate = self
        play_timer?.lgf_StopTimer()
        play_timer = nil
    }
    
    // 获取时间
    func getTime() -> String  {
        return LGFAudioPlayer.getTimeWithNum(Int(audioPlayer.progress))
    }
    func getAllTime() -> String  {
        return LGFAudioPlayer.getTimeWithNum(Int(audioPlayer.duration))
    }
    func getAllTime(_ duration: Int) -> String  {
        return LGFAudioPlayer.getTimeWithNum(duration / 1000)
    }
    @discardableResult
    class func getTimeWithNum(_ allTime: Int) -> String {
        var time: String = "00:00"
        //一个小算法，来实现00:00这种格式的播放时间
        let all: Int = allTime
        let m: Int = all % 60
        let f: Int = Int(all / 60)
        if f < 10{
            time = "0\(f):"
        } else {
            time = "\(f):"
        }
        if m < 10{
            time += "0\(m)"
        } else {
            time += "\(m)"
        }
        return time
    }
    
    //更新当前播放信息
    func updateNowPlayingInfoCenter() {
        self.delegate?.LGFAudioPlayerState(audioPlayer)
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "LGFAudioPlayerState"), object: audioPlayer)
    }
    
}

extension LGFAudioPlayer: STKAudioPlayerDelegate {
    func audioPlayer(_ audioPlayer: STKAudioPlayer, didStartPlayingQueueItemId queueItemId: NSObject) {
        
    }
    
    func audioPlayer(_ audioPlayer: STKAudioPlayer, didFinishBufferingSourceWithQueueItemId queueItemId: NSObject) {
        updateNowPlayingInfoCenter()
    }
    
    func audioPlayer(_ audioPlayer: STKAudioPlayer, stateChanged state: STKAudioPlayerState, previousState: STKAudioPlayerState) {
        self.state = state
        if state != .stopped && state != .error && state != .disposed {
        }
        updateNowPlayingInfoCenter()
    }
    
    func audioPlayer(_ audioPlayer: STKAudioPlayer, didFinishPlayingQueueItemId queueItemId: NSObject, with stopReason: STKAudioPlayerStopReason, andProgress progress: Double, andDuration duration: Double) {
        stop()
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "LGFAudioPlayerStop"), object: audioPlayer)
        self.delegate?.LGFAudioPlayerStop(audioPlayer)
    }
    
    func audioPlayer(_ audioPlayer: STKAudioPlayer, unexpectedError errorCode: STKAudioPlayerErrorCode) {
        stop()
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "LGFAudioPlayerStop"), object: audioPlayer)
        self.delegate?.LGFAudioPlayerStop(audioPlayer)
    }
    
    
}
